package org.light.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.generator.NamedStatementGenerator;
import org.light.limitedverb.CountSearchByFieldsRecords;
import org.light.utils.DomainTokenUtil;
import org.light.utils.StringUtil;
import org.light.utils.TableStringUtil;
import org.light.utils.WriteableUtil;

public class SearchByFieldsByPage extends Verb implements EasyUIPositions {
	protected CountSearchByFieldsRecords countSearch = new CountSearchByFieldsRecords();
	protected Set<Field> deniedFields = new TreeSet<>();

	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			if (StringUtil.isBlank(this.getDbType())||"MariaDB".equalsIgnoreCase(this.getDbType())||"MySQL".equalsIgnoreCase(this.getDbType())||"pgsql".equalsIgnoreCase(this.dbType)||"postgresql".equalsIgnoreCase(this.dbType)) {
				Method method = new Method();
				method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByPage");
				method.setNoContainer(false);
				method.addSignature(new Signature(1, "db","*sql.DB"));
				method.addSignature(new Signature(2, this.domain.getLowerFirstDomainName(),new Type(this.domain.getDomainSuffix()+ "." + this.domain.getType())));
				method.addSignature(new Signature(3, "ignoreMap","map[string]bool"));
				method.addSignature(new Signature(4, "pagenum","int64"));
				method.addSignature(new Signature(5, "pagesize","int64"));
				method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+ "." + this.domain.getType()));
				
				List<Writeable> sList = new ArrayList<Writeable>();
				sList.add(new Statement(1000L,1,"start := (pagenum - 1) * pagesize"));
				sList.add(new Statement(2000L,1,"limit := pagesize"));
				sList.add(new Statement(3000L,1,"query := \"select " + DomainTokenUtil.generateTableCommaFieldsWithDeniedFields(domain,this.deniedFields) + " from " + domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain)+" where 1=1 \""));
				sList.add(new Statement(4000L,0,""));
				int index = 0;
				long serial = 5000L;
				for (Field f: this.domain.getSearchFields()) {
					if (!deniedFields.contains(f)) {
						if (f.getFieldType().equals("string")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" like '%\"+"+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"()+\"%' \""));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						} else if (f.getFieldType().equals("bool")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatBool("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"())"));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						} else if (f.getFieldType().equals("int64")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatInt("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 10)"));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						} else if (f.getFieldType().equals("int32")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+fmt.Sprint("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+")"));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						}else if (f.getFieldType().equals("int")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.Itoa("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+")"));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						}else if (f.getFieldType().equals("float")||f.getFieldType().equals("float64")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatFloat("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 'f', 4, 64)"));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						}else if (f.getFieldType().equals("float32")) {
							sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatFloat("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 'f', 4, 32)"));
							sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
							sList.add(new Statement(serial+4000L,1,"}"));
						}
						serial += 5000L;
						index ++;
					}					
				}
				if (("PostgreSQL".equalsIgnoreCase(this.getDbType())||"pgsql".equalsIgnoreCase(this.getDbType()))&&this.domain.getDomainId()!=null) {
					sList.add(new Statement(serial, 1, "query += \" order by " + StringUtil.changeDomainFieldtoTableColum(domain.getDomainId().getFieldName()) + " asc \""));
					serial += 1000L;
				}				
				 
				sList.add(new Statement(serial,1,"query"+index+" := \" limit %v offset %v \""));
				sList.add(new Statement(serial+1000L,1,"query"+index+" = fmt.Sprintf(query"+index+", limit, start)"));
				sList.add(new Statement(serial+2000L,1,"query += query"+index+""));
				sList.add(new Statement(serial+3000L,0,""));
				sList.add(new Statement(serial+6000L,1,"stmt, err := db.Prepare(query)"));
				sList.add(new Statement(serial+7000L,1,"if err != nil {"));
				sList.add(new Statement(serial+8000L,2,"panic(err)"));
				sList.add(new Statement(serial+9000L,1,"}"));
				sList.add(new Statement(serial+10000L,0,""));
				sList.add(new Statement(serial+11000L,1,"rows, err := stmt.Query()"));
				sList.add(new Statement(serial+12000L,1,"if err != nil {"));
				sList.add(new Statement(serial+13000L,2,"panic(err)"));
				sList.add(new Statement(serial+14000L,1,"}"));
				
				sList.add(new Statement(serial+15000L,1,"var "+this.domain.getLowerFirstPlural()+" [] "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
				sList.add(new Statement(serial+16000L,0,""));
				sList.add(new Statement(serial+17000L,1,"for rows.Next() {"));
				serial += 18000L;
				StringBuilder sb = new StringBuilder();
				for (Field f:this.domain.getFields()) {
					sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" "+ f.getFieldTypeWithParseImage()));
					sb.append("&").append(f.getLowerFirstFieldName()).append(",");
					serial += 1000L;
				}
				String fieldsQuery = sb.toString();
				if (fieldsQuery.endsWith(",")) fieldsQuery = fieldsQuery.substring(0,fieldsQuery.length()-1);

				sList.add(new Statement(serial,0,""));
				sList.add(new Statement(serial+1000L,2,"err := rows.Scan("+fieldsQuery+")"));
				sList.add(new Statement(serial+2000L,2,"if err != nil {"));
				sList.add(new Statement(serial+3000L,3,"panic(err)"));
				sList.add(new Statement(serial+4000L,2,"}"));
				sList.add(new Statement(serial+5000L,2,"var "+this.domain.getLowerFirstDomainName()+" "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
				serial += 6000L;
				for (Field f:this.domain.getFields()) {
					sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"("+f.getLowerFirstFieldName()+")"));
					serial += 1000L;
				}
				sList.add(new Statement(serial,2,""+this.domain.getLowerFirstPlural()+" = append("+this.domain.getLowerFirstPlural()+", "+this.domain.getLowerFirstDomainName()+")"));
				sList.add(new Statement(serial+1000L,1,"}"));
				sList.add(new Statement(serial+2000L,1,"return "+this.domain.getLowerFirstPlural()+""));
				method.setMethodStatementList(WriteableUtil.merge(sList));
				return method;
			}else if (this.getDbType().equalsIgnoreCase("Oracle")) {
				return null;
			}else {
				return null;
			}
		}
	}

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByLimit");
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getLowerFirstDomainName(),this.domain.getType()));
			method.addSignature(new Signature(3, "ignoreMap","map[string]bool"));
			method.addSignature(new Signature(4, "pagenum","int64"));
			method.addSignature(new Signature(5, "pagesize","int64"));
			method.setReturnType(new Type("[] "+this.domain.getType()));			

			return method;
		}
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByPage");
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(),this.domain.getType()));
			method.addSignature(new Signature(2, "ignoreMap","map[string]bool"));
			method.addSignature(new Signature(3, "pagenum","int64"));
			method.addSignature(new Signature(4, "pagesize","int64"));
			method.setReturnType(new Type("[] "+this.domain.getType()));
			return method;
		}
	}
	@Override
	public Method generateServiceImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByPage");
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(),this.domain.getDomainSuffix()+"."+this.domain.getType()));
			method.addSignature(new Signature(2, "ignoreMap","map[string]bool"));
			method.addSignature(new Signature(3, "pagenum","int64"));
			method.addSignature(new Signature(4, "pagesize","int64"));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getType()));
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,1,"db := database.DB"));
			list.add(new Statement(3000L, 1, "return "+this.domain.getDaoimplSuffix()+".Search" + this.domain.getCapFirstPlural() + "ByFieldsByPage(db,"
					+ this.domain.getLowerFirstDomainName() + ",ignoreMap,pagenum,pagesize)"));
			method.setMethodStatementList(WriteableUtil.merge(list));
			return method;
		}
	}
	public SearchByFieldsByPage() {
		super();
		this.dbType = "MariaDB";
		this.setLabel("按字段分页搜索");
	}
	
	public SearchByFieldsByPage(String dbType) {
		super();
		this.dbType = dbType;
		this.setLabel("按字段分页搜索");
	}

	public SearchByFieldsByPage(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = "MariaDB";
		this.denied = domain.isVerbDenied("SearchByFieldsByPage");
		this.countSearch = new CountSearchByFieldsRecords(domain);
		this.setVerbName("search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByPage");
		this.setLabel("按字段分页搜索");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("SearchByFieldsByPage");
	}


	public SearchByFieldsByPage(Domain domain,String dbType) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = dbType;
		this.denied = domain.isVerbDenied("SearchByFieldsByPage");
		this.countSearch = new CountSearchByFieldsRecords(domain);
		this.setVerbName("search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByPage");
		this.setLabel("按字段分页搜索");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("SearchByFieldsByPage");
	}
	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			this.countSearch.setDomain(this.domain);

			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFieldsByPage");
			method.addSignature(new Signature(1,"c","*gin.Context"));
					
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"pagenum, _ := strconv.ParseInt(c.PostForm(\"page\"), 10, 64)"));
			sList.add(new Statement(2000L,1,"pagesize, _ := strconv.ParseInt(c.PostForm(\"rows\"), 10, 64)"));
			sList.add(new Statement(2000L,1,"ignoreMap := make(map[string]bool)"));
			long serial = 3000L;
			for (Field f : this.domain.getSearchFields()) {
				if (!deniedFields.contains(f)) {
					sList.add(new Statement(serial+1000L,1,"if c.PostForm(\""+f.getLowerFirstFieldName()+"\") == \"\" {"));
					sList.add(new Statement(serial+2000L,2,"ignoreMap[\""+f.getLowerFirstFieldName()+"\"] = true"));
					sList.add(new Statement(serial+3000L,1,"}"));
					serial += 4000L;
				}
			}
			for (Field f : this.domain.getSearchFields()) {
				if (!deniedFields.contains(f)) {
					if (f.getFieldType().equalsIgnoreCase("bool")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+", _ := strconv.ParseBool(c.PostForm(\""+f.getLowerFirstFieldName()+"\"))"));
					} else if (f.getFieldType().equalsIgnoreCase("string")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+" := c.PostForm(\""+f.getLowerFirstFieldName()+"\")"));
					} else if (f.getFieldType().equalsIgnoreCase("int64")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+", _ := strconv.ParseInt(c.PostForm(\""+f.getLowerFirstFieldName()+"\"), 10, 64)"));
					} else if (f.getFieldType().equalsIgnoreCase("int")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+", _ := strconv.Atoi(c.PostForm(\""+f.getLowerFirstFieldName()+"\"))"));
					}else if (f.getFieldType().equalsIgnoreCase("int32")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+", _ := strconv.ParseInt(c.PostForm(\""+f.getLowerFirstFieldName()+"\"), 10, 32)"));
					} else if (f.getFieldType().equalsIgnoreCase("float")||f.getFieldType().equalsIgnoreCase("float64")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+", _ := strconv.ParseFloat(c.Query(\""+f.getLowerFirstFieldName()+"\"), 64)"));
					} else if (f.getFieldType().equalsIgnoreCase("float32")) {
						sList.add(new Statement(serial,1,f.getLowerFirstFieldName()+", _ := strconv.ParseFloat(c.Query(\""+f.getLowerFirstFieldName()+"\"), 32)"));
					}
					serial += 1000L;
				}
			}
			sList.add(new Statement(serial,1,""+this.domain.getLowerFirstDomainName()+" := "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+"{"));
			serial += 1000L;
			for (Field f : this.domain.getSearchFields()) {
				if (!deniedFields.contains(f)) {
					if (f.getFieldType().equalsIgnoreCase("int32")) sList.add(new Statement(serial,2,f.getCapFirstFieldName()+":      int32("+f.getLowerFirstFieldName()+"),"));
					else sList.add(new Statement(serial,2,f.getCapFirstFieldName()+":      "+f.getLowerFirstFieldName()+","));
					serial += 1000L;
				}
			}
			sList.add(new Statement(serial,1,"}"));
			sList.add(new Statement(serial+1000L,0,""));
			sList.add(new Statement(serial+2000L,1,"total := "+this.domain.getServiceimplSuffix()+".CountSearch"+this.domain.getCapFirstPlural()+"ByFieldsRecords("+this.domain.getLowerFirstDomainName()+",ignoreMap)"));
			sList.add(new Statement(serial+3000L,1,""+this.domain.getLowerFirstPlural()+" := "+this.domain.getServiceimplSuffix()+".Search"+this.domain.getCapFirstPlural()+"ByFieldsByPage("+this.domain.getLowerFirstDomainName()+",ignoreMap, pagenum, pagesize)"));
			sList.add(new Statement(serial+4000L,1,"SendResponse(c, nil, "+this.domain.getLowerFirstPlural()+", total, true)"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName("search" + domain.getPlural() + "ByFieldsByPage");

			StatementList sl = new StatementList();
			sl.add(new Statement(1000, 1, "params = {"));
			long serial = 2000;
			for (Field f : domain.getSearchFields()) {
				if (!deniedFields.contains(f)) {
					if (f instanceof Dropdown)
						sl.add(new Statement(serial, 2, f.getLowerFirstFieldName() + ":$(\"#ffsearch\").find(\"#"
								+ f.getLowerFirstFieldName() + "\").combobox(\"getValue\"),"));
					else if (!f.getFieldType().equalsIgnoreCase("boolean"))
						sl.add(new Statement(serial, 2, f.getLowerFirstFieldName() + ":$(\"#ffsearch\").find(\"#"
								+ f.getLowerFirstFieldName() + "\").val(),"));
					else
						sl.add(new Statement(serial, 2, f.getLowerFirstFieldName()
								+ ":parseBoolean($(\"#ffsearch\").find(\"#" + f.getLowerFirstFieldName() + "\").val()),"));
					serial += 1000;
				}
			}
			sl.add(new Statement(serial, 1, "};"));
			sl.add(new Statement(serial + 1000, 1, "$(\"#dg\").datagrid({queryParams:params});"));

			method.setMethodStatementList(sl);
			return method;
		}
	}

	public CountSearchByFieldsRecords getCountSearch() {
		return countSearch;
	}

	public void setCountSearch(CountSearchByFieldsRecords countSearch) {
		this.countSearch = countSearch;
	}

	public Set<Field> getDeniedFields() {
		return deniedFields;
	}

	public void setDeniedFields(Set<Field> deniedFields) {
		this.deniedFields = deniedFields;
	}
}
